var mongoose = require('./db.js');

var ObjectId = require('mongoose').Types.ObjectId; 

var commentSchema = mongoose.Schema({
	userName: String,
	postId: String,
    postAuthor: String,
	content: String,
    inPrivate: Boolean,
	time: String
});

var Comment = mongoose.model('Comment', commentSchema);

var commentDAO = function(){};

commentDAO.prototype.addComment = function (content, userName, callback){
	var c = new Comment(content);
	c.userName = userName;
	c.time = (new Date()).valueOf();

	c.save(function(e){
		callback(e, c);
	});
};

commentDAO.prototype.countByPostId = function (postId, callback){
	Comment.find({postId: postId}).count(callback);
};

commentDAO.prototype.findByPostId = function (postId, userName, callback){

    if(userName){
        Comment.find({postId: postId, $or :[ {userName: userName}, {postAuthor: userName} ] }).exec(function(e, comments){
            if(e){
                callback(null, e);
            } else {
                callback(comments);
            }
        });
    } else {
        Comment.find({postId: postId, inPrivate: {$ne: true} }).exec(function(e, comments){
            if(e){
                callback(null, e);
            } else {
                callback(comments);
            }
        });
    }

};

commentDAO.prototype.deleteCommentById = function (id, callback) {
	Comment.remove({_id: id}, callback);
};

commentDAO.prototype.deleteCommentsByUserName = function(name, callback){
	Comment.remove({userName: name}, callback);
}

module.exports = new commentDAO();